// utils/simple-cache.ts - 简化的缓存系统
/** 缓存项 */
interface CacheItem {
  data: any;
  timestamp: number;
  expiry: number;
}

/** 简单缓存管理器 */
export class SimpleCache {
  private static PREFIX = 'smart_water_cache_';
  
  /** 设置缓存 */
  static set(key: string, data: any, expireMinutes: number = 10): void {
    try {
      const item: CacheItem = {
        data,
        timestamp: Date.now(),
        expiry: Date.now() + (expireMinutes * 60 * 1000)
      };
      
      wx.setStorageSync(this.PREFIX + key, JSON.stringify(item));
    } catch (error) { 
      console.warn('[SimpleCache] 设置缓存失败:', error);
    }
  }
  
  /** 获取缓存 */
  static get(key: string): any | null {
    try {
      const cached = wx.getStorageSync(this.PREFIX + key);
      if (!cached) return null;
      
      const item: CacheItem = JSON.parse(cached);
      
      // 检查是否过期
      if (Date.now() > item.expiry) {
        this.remove(key);
        return null;
      }
      
      return item.data;
    } catch (error) {
      console.warn('[SimpleCache] 获取缓存失败:', error);
      return null;
    }
  }
  
  /** 删除缓存 */
  static remove(key: string): void {
    try {
      wx.removeStorageSync(this.PREFIX + key);
    } catch (error) {
      console.warn('[SimpleCache] 删除缓存失败:', error);
    }
  }
  
  /** 清空所有缓存 */
  static clear(): void {
    try {
      const info = wx.getStorageInfoSync();
      const keys = info.keys.filter(key => key.startsWith(this.PREFIX));
      
      keys.forEach(key => {
        try {
          wx.removeStorageSync(key);
        } catch (error) {
          console.warn('[SimpleCache] 删除缓存项失败:', key);
        }
      });
    } catch (error) {
      console.error('[SimpleCache] 清空缓存失败:', error);
    }
  }
  
  /** 清理过期缓存 */
  static cleanup(): void {
    try {
      const info = wx.getStorageInfoSync();
      const keys = info.keys.filter(key => key.startsWith(this.PREFIX));
      const now = Date.now();
      
      keys.forEach(key => {
        try {
          const cached = wx.getStorageSync(key);
          if (cached) {
            const item: CacheItem = JSON.parse(cached);
            if (now > item.expiry) {
              wx.removeStorageSync(key);
            }
          }
        } catch (error) {
          // 数据损坏，直接删除
          wx.removeStorageSync(key);
        }
      });
    } catch (error) {
      console.error('[SimpleCache] 清理过期缓存失败:', error);
    }
  }
}

/** 带缓存的API调用 */
export async function cachedApiCall<T>(
  cacheKey: string,
  apiCall: () => Promise<T>,
  expireMinutes: number = 10
): Promise<T> {
  // 先尝试获取缓存
  const cached = SimpleCache.get(cacheKey);
  if (cached) {
    console.log('[Cache] 缓存命中:', cacheKey);
    return cached;
  }
  
  // 缓存未命中，调用API
  try {
    const result = await apiCall();
    
    // 保存到缓存
    SimpleCache.set(cacheKey, result, expireMinutes);
    
    return result;
  } catch (error) {
    console.error('[Cache] API调用失败:', error);
    throw error;
  }
}

export default SimpleCache;
